package cn.tradewin.common.util;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.whalin.MemCached.MemCachedClient;
import com.whalin.MemCached.SockIOPool;

public class MemcachedUtil {

	// create a static client as most installs only need a single instance
	private static Properties prop;
	private static Logger log = LoggerFactory.getLogger(MemcachedUtil.class);
	private static MemCachedClient mcc = new MemCachedClient();

	// set up connection pool once at class load
	static {
		try {
			prop = ResourcesUtils.getResourceAsProperties("memcached.properties");
		} catch (IOException e) {
			e.printStackTrace();
			log.error("please configure memcached information in memcached.properties file");
		}
		// server list and weights
		String[] servers = prop.getProperty("addressList").split(",");
		String[] weight = prop.getProperty("weights").split(",");
		Integer[] weights = new Integer[weight.length];
		int i = 0;
		for (String s : weight) {
			weights[i++] = Integer.parseInt(s);
		}
		// grab an instance of our connection pool
		SockIOPool pool = SockIOPool.getInstance();

		// set the servers and the weights
		pool.setServers(servers);
		pool.setWeights(weights);
		pool.setHashingAlg(SockIOPool.CONSISTENT_HASH);  

		// set some basic pool settings
		// 5 initial, 5 min, and 250 max conns
		// and set the max idle time for a conn
		// to 6 hours
		pool.setInitConn(Integer.parseInt(prop.getProperty("memcached-initConn")));
		pool.setMinConn(Integer.parseInt(prop.getProperty("memcached-minConn")));
		pool.setMaxConn(Integer.parseInt(prop.getProperty("memcached-maxConn")));
		pool.setMaxIdle(1000 * 60 * 60 * 6);

		// set the sleep for the maint thread
		// it will wake up every x seconds and
		// maintain the pool size
		pool.setMaintSleep(Integer.parseInt(prop.getProperty("memcached-maintSleep")));

		// set some TCP settings
		// disable nagle
		// set the read timeout to 3 secs
		// and don't set a connect timeout
		pool.setNagle(false);
		pool.setSocketTO(3000);
		pool.setSocketConnectTO(0);
		pool.setFailover(true);

		// initialize the connection pool
		pool.initialize();

		// lets set some compression on for the client
		// compress anything larger than 64k
		// mcc.setCompressEnable( true );
		// mcc.setCompressThreshold( 64 * 1024 );
	}

	public static MemCachedClient getMemcachedClient() {
		return mcc;
	}
}
